<template>
  <div class="container-box">
    <!-- 回到顶部-->
    <el-backtop target=".content-container"></el-backtop>
    <!--搜索组件-->
    <div class="form-box">
      <el-form :model="selDateFrom" ref="selDateFrom">
        <el-row class="input-box" :gutter="20">
          <div class="left">
            <div class="search-btn" @click="search">
              <i class="el-icon-my-search-screen"></i>
              <span class="fun-name">筛选</span>
            </div>
          </div>
          <div class="left">
            <div class="search-btn" @click="deleteMail">
              <i class="el-icon-my-search-delete"></i>
              <span class="fun-name">删除</span>
            </div>
          </div>
          <div class="left">
            <el-tooltip content="点击识别失败的邮件，手动下载邮件中的发票，然后点击该按钮上传至系统" placement="top" effect="light">
              <div class="search-btn" @click="uploadInvoiceFile">
                <i class="el-icon-my-search-upload"></i>
                <span class="fun-name">上传</span>
              </div>
            </el-tooltip>
          </div>
          <div class="right w200">
            <el-input class="" placeholder="发件人、收件人" @keyup.enter.native="searchName" size="small" v-model="selDateFrom.serachManyName">
              <i slot="suffix" class="el-input__icon el-icon-search" @click.prevent="searchName"></i>
            </el-input>
          </div>
        </el-row>
      </el-form>
    </div>
    <!--分页列表-->
    <iTable v-if="pageObj.total>0" :tableData="tableData" class="listTable"  :columns="columns" :loading="loading" :pageObj="pageObj" :tableFun="tableFun" ref="mutipleTable" >
      <el-table-column slot="recognitionStutasName" label="识别状态" align="center" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.recognitionStutas === '1'" class="line-danger">{{scope.row.recognitionStutasName}}</span>
          <span v-else class="line-success">{{scope.row.recognitionStutasName}}</span>
        </template>
      </el-table-column>
      <el-table-column slot="sourceStatusName" label="来源" align="center" width="120">
        <template slot-scope="scope">
          <span v-if="scope.row.sourceStatus === '1'" >{{scope.row.sourceStatusName}}</span>
          <span v-else class="line-info">{{scope.row.sourceStatusName}}</span>
        </template>
      </el-table-column>
    </iTable>
    <div class="listNull" v-else>
      <i class="el-icon-my-list-null"></i>
      <div class="list-null-text">赶紧去获取发票吧</div>
    </div>
    <!--弹出框-->
    <el-dialog :title="dialog.title" :visible.sync="dialog.dialogVisible" :center="true">
      <el-upload
        v-if="dialog.type === '2'"
        class="upload-demo"
        ref="upload_invoice"
        drag
        :data="{invoiceMailId: dialog.id, userId: userId}"
        name="upload_file"
        :action="uploadUrl"
        :on-success="fileUpload"
        :on-error="fileUploadError"
        :on-remove="removeImgs"
        accept=".jpg,.pdf,.png"
        >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传 jpg/png/pdf 发票原文件</div>
      </el-upload>
      <div v-else>
        <el-form :model="dialog.form">
          <el-form-item label="发送日期：" :label-width="dialog.formLabelWidth">
            <el-date-picker
              v-model="dialog.form.sendDate"
              :disabled="dialog.detail"
              type="datetime"
              placeholder="发送日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="发件人：" :label-width="dialog.formLabelWidth">
            <el-input v-model="dialog.form.sender" :disabled="dialog.detail" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="收件人：" :label-width="dialog.formLabelWidth">
            <el-input v-model="dialog.form.addressee" :disabled="dialog.detail" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="邮件主题：" :label-width="dialog.formLabelWidth">
            <el-input v-model="dialog.form.mailTheme" :disabled="dialog.detail" autocomplete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer" v-show="!dialog.detail" style="text-align: center;">
          <el-button @click="dialog.dialogVisible = false">关 闭</el-button>
          <el-button type="primary" @click="dialogAdd">确 定</el-button>
        </div>
      </div>
    </el-dialog>
    <!--搜索弹出框-->
    <el-dialog :title="searchDialog.title" :width="searchDialog.width" :top="searchDialog.top" :modal="searchDialog.modal" :visible.sync="searchDialog.dialogVisible" :center="true">
      <el-form :model="searchDialog.form">
        <el-form-item label="邮件来源：" :label-width="searchDialog.formLabelWidth">
          <div class="left w150">
            <el-select size="small" v-model="selDateFrom.sourceStatus" placeholder="请选择邮件来源">
              <el-option
                v-for="item in sourceStatusDateList"
                :key="item.baseId"
                :label="item.baseName"
                :value="item.baseCodeValue"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
        <el-form-item label="识别状态：" :label-width="searchDialog.formLabelWidth">
          <div class="left w150">
            <el-select size="small" v-model="selDateFrom.recognitionStutas" placeholder="请选择识别状态">
              <el-option
                v-for="item in recognitionStutasDateList"
                :key="item.baseId"
                :label="item.baseName"
                :value="item.baseCodeValue"
              ></el-option>
            </el-select>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" v-show="!searchDialog.detail" style="text-align: center;">
        <el-button @click="resetForm">重 置</el-button>
        <el-button type="primary" @click="selForm">筛 选</el-button>
      </div>
    </el-dialog>
    <chooseDialog :show.sync="chooseVisible"></chooseDialog>

  </div>
</template>
<script>
  import iTable from "common/iTable";
  import chooseDialog from "common/chooseDialog";
  import { mapMutations,mapGetters } from "vuex";
  import * as types from "../../store/mutation-types";
  import {baseUrl} from 'config/index.js'
  import * as commonApi from "api/common";

  export default {
    components: {
      iTable,chooseDialog,
    },
    beforeRouteLeave(to, from, next) { //判断路由的跳转 详情页面返回则不要更新页面数据
      if (to.path === '/mail/mailDetail'){ //详情
        this.setDetailStatus('2')
      }
      next();
    },
    // beforeRouteEnter(to, from, next){
    //   if (from.path === '/mail/mailDetail'){ //详情
    //   }
    // },
    data() {
      return {
        uploadUrl: baseUrl + '/webs/upload',
        columns: [ //列表头
          {label: '邮件主题', prop: 'mailTheme', width: '260', align: 'left'},
          {label: '发送日期', prop: 'sendDate', width: '160', align: 'left'},
          {slot: 'recognitionStutasName'},
          {slot: 'sourceStatusName'},
          {label: '发件人', prop: 'sender', width: '300', align: 'left'},
          {label: '收件人', prop: 'addressee', width: '300', align: 'left'},
          {label: '', prop: 'none', align: 'left'},
          // {slot: 'operate'} // 操作列
        ],
        loading: false,
        tableFun: { //列表函数
          rowClick:((row, event, column) =>{ //行点击事件
            this.mailInfo(row, event, column)
          }),
        },
        pageObj: { //分页列表参数
          id: 'invoiceMailId', //分页数据中的主键id
          sizes: [10, 20, 50, 100], //分页数
          size: 10, //当前分页数
          total: 0, //总数
          currentPage: 1, //当前页
          pageFunc:(currentPage) =>{ //点击分页
            this.receiveCurrentPage(currentPage)
          },
          pageSizeFunc:(currentPage) =>{ //改变分页尺寸
            this.receivePageSize(currentPage)
          }
        },
        tableData: [], //列表数据
        operationIndex: '', //操作按钮状态控制
        selDateFrom: {
          sender: "", //发件人姓名
          serachManyName: '',//名称批量搜索
          sourceStatus: '', //邮件来源
          recognitionStutas: '', //识别状态
        },
        sourceStatusDateList: [],
        recognitionStutasDateList: [],
        userId: '',
        dialog:{ //文件上传，修改 详情弹出框
          id: '', //唯一标识
          title: '', //弹出框标题
          type: '', //类型 2文件上传 1邮件信息
          dialogVisible: false, //是否显示弹窗框
          detail: false, //是否展示位详情
          formLabelWidth: '120px', //label的宽度
          form:{}, //表单内容
        },
        searchDialog:{
          title: '', //弹出框标题
          width: '450px', //弹出框宽度
          top: '27vh', //margin-top 值
          modal: false, //是否需要遮罩层
          dialogVisible: false, //是否显示弹窗框
          detail: false, //是否展示位详情
          formLabelWidth: '90px', //label的宽度
          form:{}, //表单内容
        },
        chooseVisible: false, //用户选择dialog
      };
    },
    activated(){
      console.log('----------mailList activated-------------')
      if (this.detailStatus != '2'){
        this.getMailDate()
      }
      this.setDetailStatus('1')
    },
    created() {
      console.log('----------mailList created-------------')
      let user = JSON.parse(sessionStorage.getItem("user"))
      this.userId = user.userId
      this.getMailDate()
      this.getRecognitionStutasDateList()
      this.getSourceStatusDateList()
    },
    mounted() {
    },
    computed: {
      ...mapGetters(["detailStatus"])
    },
    methods: {
      receivePageSize(val) { //改变当前页大小
        this.pageObj.currentPage = 1
        this.pageObj.size = val
        this.getMailDate()
      },
      receiveCurrentPage(val) { //页码切换
        this.pageObj.currentPage = val
        this.getMailDate()
      },
      showOperation: function (e) { //分页列表操作点击事件
        this.operationIndex = e
      },
      hideOperation: function (e) { // 分页列表操作隐藏事件
        if (this.operationIndex == e) {
          this.operationIndex = ''
        }
      },
      detail: function(e, type){ //邮件详情
        this.findInvoiceMail(e.invoiceMailId)
        this.dialog.id = e.invoiceMailId
        this.dialog.type = type
        this.dialog.title = '邮件详情'
        this.dialog.detail = true
        this.dialog.dialogVisible = true
      },
      uploadInvoiceFile(){
        let arr = this.$refs.mutipleTable.selectDataArrL // 获取勾选的值
        if (arr == null || arr.length === 0){
          this.$msg({text: '请勾选邮件', type: 'info'})
          return
        }
        if (arr.length > 1){
          this.$msg({text: '请选择单个邮件', type: 'info'})
          return
        }
        let id = arr[0]
        let mail = this.tableData.find(item => item.invoiceMailId == id)
        if (mail != undefined && mail.recognitionStutas != 1){
          this.$msg({text: '请选择识别失败的邮件', type: 'info'})
          return
        }
        const params = {invoiceMailId: id}
        this.uploadInvoice(params, '2')
      },
      uploadInvoice: function(e, type){ //发票上传
        this.dialog.id = e.invoiceMailId
        this.dialog.type = type
        this.dialog.title = '上传发票'
        this.dialog.detail = true
        this.dialog.dialogVisible = true
      },
      mailInfo(row, event, column){ //邮件内容
        this.$router.push({name:'mailDetail', params:{invoiceMailId: row.invoiceMailId}})
      },
      fileUpload(response, file, fileList){
        this.dialog.dialogVisible = false
        this.removeImgs()
        if (response.status === 200){
          if (response.data.result){
            this.$msg({text: response.data.msg, type: 'success'})
            this.getMailDate()
          } else {
            this.$msg({text: response.data.msg, type: 'error'})
          }
        } else {
          this.$msg({text: '文件识别错误', type: 'error'})
        }
      },
      fileUploadError(err, file, fileList){
        debugger
        console.log(err)
        this.$msg({text: '上传失败', type: 'error'})
      },
      removeImgs(file, fileList){
        this.$refs.upload_invoice.clearFiles();
      },
      dialogAdd: function(){ //弹出框确认事件
        const data = this.dialog.form
        const params = {
          invoiceMailId: this.dialog.id,
          sender: data.sender,
          sendDate: data.sendDate,
          addressee: data.addressee,
          mailTheme: data.mailTheme,
        }
        this.updateInvoiceMail(params)
      },
      //筛选点击事件
      search(){
        this.searchDialog.dialogVisible = true
      },
      resetForm(){ //重置表单
        this.selDateFrom.sender = ''
        this.selDateFrom.recognitionStutas = ''
        this.selDateFrom.sourceStatus = ''
      },
      selForm(){ //查询
        this.searchDialog.dialogVisible = false
        this.pageObj.currentPage = 1
        this.getMailDate()
      },
      searchName(){ //搜索查询
        this.pageObj.currentPage = 1
        this.getMailDate()
      },
      getMailDate(){ //获取邮件列表数据
        this.loading = true
        const params = {}
        params.userId = this.userId
        params.limit = this.pageObj.size
        params.offset = (this.pageObj.currentPage - 1) * this.pageObj.size
        params.sender = this.selDateFrom.sender
        params.serachManyName = this.selDateFrom.serachManyName
        params.recognitionStutas = this.selDateFrom.recognitionStutas
        params.sourceStatus = this.selDateFrom.sourceStatus
        commonApi.findInvoiceMailList(params).then(res => {
          this.loading = false
          let {data} = res;
          if (data.status === 200) {
            this.pageObj.total = data.data.total
            this.tableData = data.data.rows
          }
        })
      },
      deleteMail(){ //删除邮件
        let arr = this.$refs.mutipleTable.selectDataArrL // 获取勾选的值
        if (arr == null || arr.length === 0){
          this.$msg({text: '请勾选邮件！', type: 'info'})
          return
        }
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          const params = {invoiceMailIds: arr}
          commonApi.deleteInvoiceMail(params).then(res => {
            let {data} = res;
            if (data.status === 200) {
              if (data.data.result){
                this.$msg({text: data.data.msg, type: 'success'})
                // 刷新列表
                this.pageObj.currentPage = 1
                this.getMailDate()
              } else {
                this.$msg({text: data.data.msg, type: 'error'})
              }
            } else {
              this.$msg({text: '删除失败', type: 'error'})
            }
          })
        }).catch(() => {
          console.log('取消刪除')
        });
      },
      getSourceStatusDateList(){ //邮件来源
        const params = {baseCode: "INVOICE_MAIL_SOURCE"}
        commonApi.getBaseDateList(params).then(res => {
          let {data} = res;
          if (data.status === 200) {
            this.sourceStatusDateList = data.data
          }
        })
      },
      getRecognitionStutasDateList(){ //识别状态
        const params = {baseCode: "INVOICEC_MAIL_RECOGNITION_STATUS"}
        commonApi.getBaseDateList(params).then(res => {
          let {data} = res;
          if (data.status === 200) {
            this.recognitionStutasDateList = data.data
          }
        })
      },
      findInvoiceMail(id){ //查询发票邮件详情
        const params = {invoiceMailId: id}
        commonApi.findInvoiceMail(params).then(res => {
          let {data} = res;
          if (data.status === 200) {
            this.dialog.form = data.data
          }
        }).catch(() => {
          this.$msg({text: '查询异常', type: 'error'})
        })
      },
      updateInvoiceMail(params){ //更新邮件内容
        commonApi.updateInvoiceMail(params).then(res => {
          let {data} = res;
          this.dialog.dialogVisible = false
          if (data.status === 200) {
            if (data.data.result){
              this.$msg({text: data.data.msg, type: 'success'})
              // 刷新列表
              this.getMailDate()
            } else {
              this.$msg({text: data.data.msg, type: 'error'})
            }
          }
        }).catch(() => {
          this.dialog.dialogVisible = false
          this.$msg({text: '更新异常', type: 'error'})
        })
      },
      ...mapMutations({
        setDetailStatus : types.SET_DETAILSTATUS,
      })
    },
  };
</script>

<!--组件样式 本页面修改-->
<style scoped lang="scss">
  :focus{
    outline: none;
  }
  .choose-dialog{
    /deep/ .el-card{
      background: #3a8ee6;
    }
  }
</style>
<style scoped lang="scss">
  @import "../../assets/css/them";
  @media screen and (max-width: 1600px){
    .container-box {
      .form-title{
        background: #F5F5FB;
        padding-bottom: 20px;
        .el-icon-my-title {
          width: 20px;
          background: url("../../assets/img/list@2x.png") center no-repeat;
          background-size: 20px;
          line-height: 2;
          margin-right: 16px;
        }
        .el-icon-my-title:before {
          content: "替";
          visibility: hidden;
        }
        .form-title-text{
          display: inline-block;
          color: #858993;
          font-size:14px;
        }
      }
      /*搜索组件*/
      .form-box {
        padding: 15px 20px 15px 20px;
        background: $globalColor;
        position: fixed;
        margin-top: -52px;
        border-radius: 20px;
        z-index: 99;
        width: calc(100% - 210px);
        .input-box {
          margin-bottom: 5px;
          .search-btn{
            cursor: pointer;
            font-size: 16px;
            font-weight: 400;
            color: #000000;
            .fun-name{
              font-size: 14px;
              font-weight: 400;
              margin-left: 4px;
            }
            /*筛选*/
            .el-icon-my-search-screen {
              background: url("../../assets/img/screen.png") center no-repeat;
              background-size: 18px;
              width: 18px;
              line-height: 2;
            }
            .el-icon-my-search-screen:before {
              content: "替";
              visibility: hidden;
            }
            .el-icon-my-search-delete{
              background: url("../../assets/img/del@2x.png") center no-repeat;
              background-size: 18px;
              width: 18px;
              line-height: 2;
            }
            .el-icon-my-search-delete:before {
              content: "替";
              visibility: hidden;
            }
            .el-icon-my-search-upload{
              background: url("../../assets/img/upload.png") center no-repeat;
              background-size: 18px;
              width: 18px;
              line-height: 2;
            }
            .el-icon-my-search-upload:before {
              content: "替";
              visibility: hidden;
            }
          }
        }
        .input-label div {
          padding: 0px !important;
        }
        .input-label .label {
          margin-top: 4px;
        }
        .el-form{
          /deep/ .el-input--small .el-input__inner{
            border-radius: 16px;
          }
        }
      }
      .listNull{ //空数据列表
        margin-top: 52px;
        min-height: 230px;
        width: 100%;
        text-align: center;
        .el-icon-my-list-null{
          background: url("../../assets/img/data-null.png") center no-repeat;
          width: 284px;
          line-height: 221px;
          margin-top: 4%;
        }
        .el-icon-my-list-null:before {
          content: "替";
          visibility: hidden;
        }
        .list-null-text{
          margin-top: 20px;
          font-size:14px;
          font-weight:400;
          color:rgba(153,153,153,1);
          line-height:18px;
        }
      }
      .upload-demo{
        text-align: center;
      }
      // 回到顶部
      .el-backtop{
        background-color: #e3effd;
        bottom: 150px !important;
      }
    }
  }
  @media screen and (min-width: 1600px){
    .container-box {
      .form-title{
        background: #F5F5FB;
        padding-bottom: 20px;
        .el-icon-my-title {
          width: 20px;
          background: url("../../assets/img/list@2x.png") center no-repeat;
          background-size: 20px;
          line-height: 2;
          margin-right: 16px;
        }
        .el-icon-my-title:before {
          content: "替";
          visibility: hidden;
        }
        .form-title-text{
          display: inline-block;
          color: #858993;
          font-size:14px;
        }
      }
      .form-box {
        padding: 15px 20px 15px 20px;
        background: $globalColor;
        position: fixed;
        margin-top: -52px;
        border-radius: 20px;
        z-index: 99;
        width: calc(100% - 300px);
        .input-box {
          margin-bottom: 5px;
          .search-btn{
            cursor: pointer;
            font-size: 16px;
            font-weight: 400;
            color: #000000;
            .fun-name{
              font-size: 16px;
              font-weight: 400;
              margin-left: 8px;
            }
            /*筛选*/
            .el-icon-my-search-screen {
              background: url("../../assets/img/screen.png") center no-repeat;
              background-size: 20px;
              width: 20px;
              line-height: 2;
            }
            .el-icon-my-search-screen:before {
              content: "替";
              visibility: hidden;
            }
            .el-icon-my-search-delete{
              background: url("../../assets/img/del@2x.png") center no-repeat;
              background-size: 20px;
              width: 20px;
              line-height: 2;
            }
            .el-icon-my-search-delete:before {
              content: "替";
              visibility: hidden;
            }
            .el-icon-my-search-upload{
              background: url("../../assets/img/upload.png") center no-repeat;
              background-size: 20px;
              width: 20px;
              line-height: 2;
            }
            .el-icon-my-search-upload:before {
              content: "替";
              visibility: hidden;
            }
          }
        }
        .input-label div {
          padding: 0px !important;
        }
        .input-label .label {
          margin-top: 4px;
        }
        .el-form{
          /deep/ .el-input--small .el-input__inner{
            border-radius: 16px;
          }
        }
      }
      .listNull{ //空数据列表
        margin-top: 52px;
        min-height: 230px;
        width: 100%;
        text-align: center;
        .el-icon-my-list-null{
          background: url("../../assets/img/data-null.png") center no-repeat;
          width: 284px;
          line-height: 221px;
          margin-top: 12%;
        }
        .el-icon-my-list-null:before {
          content: "替";
          visibility: hidden;
        }
        .list-null-text{
          margin-top: 20px;
          font-size:14px;
          font-weight:400;
          color:rgba(153,153,153,1);
          line-height:18px;
        }
      }
      .upload-demo{
        text-align: center;
      }
      // 回到顶部
      .el-backtop{
        background-color: #e3effd;
        bottom: 150px !important;
      }
    }
  }


</style>
